package com.linln.common.utils;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpDelete;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.conn.ClientConnectionManager;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.conn.ssl.SSLSocketFactory;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
/**
 * @author : pengliang
 * @version V1.0
 * @Project: timo
 * @Package com.linln.common.utils
 * @Descriptio /**
 * @Project: timo
 * @Package com.linln.common.utils
 * @Description: 查询违章记录工具类
 * @date Date : 2020年11月20日 9:54
 */
public class ViolationHttpUtils {


    /**
     * @param plate    车牌
     * @param engineno 发动机号
     * @param frameno  车架号
     * @return
     */
    public static net.sf.json.JSONObject queryViolation(String plate, String engineno, String frameno) {

//        String result = "{\n" +
//                "  \"lsprefix\": \"赣\",\n" +
//                "  \"lsnum\": \"MY8232\",\n" +
//                "  \"carorg\": \"anhui\",\n" +
//                "  \"usercarid\": 1625000,\n" +
//                "  \"count\": 2,\n" +
//                "  \"totalprice\": 400,\n" +
//                "  \"totalscore\": 6,\n" +
//                "  \"list\": [\n" +
//                "    {\n" +
//                "      \"time\": \"2020-08-27 07:58:00\",\n" +
//                "      \"address\": \"杭长高速356公里400米\",\n" +
//                "      \"content\": \"驾驶中型以上载客载货汽车、危险物品运输车辆以外的其他机动车在高速公路上行驶超过规定时速10%未达20%的\",\n" +
//                "      \"legalnum\": \"13523\",\n" +
//                "      \"price\": 200,\n" +
//                "      \"score\": 3,\n" +
//                "      \"agency\": \"江西省公安厅交通管理局高速公路交通警察总队直属一支队第五大队\",\n" +
//                "      \"province\": \"江西\",\n" +
//                "      \"city\": \"\",\n" +
//                "      \"number\": \"3631057900449486\",\n" +
//                "      \"docnumber\": null,\n" +
//                "      \"illegalid\": 24079575,\n" +
//                "      \"town\": \"\",\n" +
//                "      \"canhandle\": 0\n" +
//                "    },\n" +
//                "    {\n" +
//                "      \"time\": \"2020-08-27 07:46:00\",\n" +
//                "      \"address\": \"南昌绕城高速29公里750米\",\n" +
//                "      \"content\": \"机动车违反禁止标线指示的\",\n" +
//                "      \"legalnum\": \"1345\",\n" +
//                "      \"price\": 200,\n" +
//                "      \"score\": 3,\n" +
//                "      \"agency\": \"江西省公安厅交通管理局高速公路交通警察总队直属一支队第二大队\",\n" +
//                "      \"province\": \"江西\",\n" +
//                "      \"city\": \"\",\n" +
//                "      \"number\": \"3631024001098518\",\n" +
//                "      \"docnumber\": null,\n" +
//                "      \"illegalid\": 24079576,\n" +
//                "      \"town\": \"\",\n" +
//                "      \"canhandle\": 0\n" +
//                "    }\n" +
//                "  ]\n" +
//                "}";
//        result =  result.replaceAll("null", "\"\"");
//        net.sf.json.JSONObject resultarr1 = net.sf.json.JSONObject.fromObject(result);
//        return resultarr1;

        String host = "http://jisuqgclwz.market.alicloudapi.com";
//      String carorg = "anhui";
//		String engineno = "0529382"; //发动机号 根据管局需要输入（100为全部输入，0为不输入）
//		String frameno = "149825"; //车架号 根据管局需要输入（100为全部输入，0为不输入）
        String iscity = "1";  //是否返回城市 1返回 默认0不返回 不一定100%返回结果，准确度90% town、lat、lng仅供参考
//		String lsnum = "MY8232"; //车牌剩余部分
//		String lsprefix = "赣"; //车牌前缀
        String lsprefix = plate.substring(0, 1);
        String lsnum = plate.substring(1);
        String lstype = "";    //车牌类型（ 01:大型汽车号牌 02:小型汽车号牌 03:使馆汽车号牌 04:领馆汽车号牌 05:境外汽车号牌 06:外籍汽车号牌 07:两、三轮摩托车号牌 08:轻便摩托车号牌 09:使馆摩托车号牌 10:领馆摩托车号牌 11:境外摩托车号牌 12:外籍摩托车号牌 13:农用运输车号牌 14:拖拉机号牌15:挂车号牌 16:教练汽车号牌 17:教练摩托车号牌 18:试验汽车号牌 19:试验摩托车号牌 20:临时入境汽车号牌 21:临时入境摩托车号牌 22:临时行驶车号牌 23:警用汽车号牌 24:警用摩托号牌 25:原农机号牌 26:香港入出境车号牌 27:澳门入出境车号牌 51:大型新能源汽车号牌 52:小型新能源汽车号牌）

        String path = "/illegal/query";
        Map<String, String> headers = new HashMap<String, String>();
        headers.put("Authorization", "APPCODE 3a9679880b504e8da28c9a153ae2da53");
        headers.put("Content-Type", "application/json; charset=UTF-8");
        // query
        Map<String, String> querys = new HashMap<String, String>();
//        querys.put("carorg", carorg);
        querys.put("engineno", engineno);
        querys.put("frameno", frameno);
        querys.put("iscity", iscity);
        querys.put("lsnum", lsnum);
        querys.put("lsprefix", lsprefix);
        querys.put("lstype", lstype);
        try {
            HttpResponse response = ViolationHttpUtils.doGet(host, path, "GET", headers, querys);
            // response Head
//             System.out.println(response.toString());
            String result = EntityUtils.toString(response.getEntity());
            result =  result.replaceAll("null", "\"\"");
            net.sf.json.JSONObject json = net.sf.json.JSONObject.fromObject(result);
            return json;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * get
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @return
     * @throws Exception
     */
    public static HttpResponse doGet(String host, String path, String method, Map<String, String> headers,
                                     Map<String, String> querys) throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpGet request = new HttpGet(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        return httpClient.execute(request);
    }

    /**
     * post form
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param bodys
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers,
                                      Map<String, String> querys, Map<String, String> bodys) throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (bodys != null) {
            List<NameValuePair> nameValuePairList = new ArrayList<NameValuePair>();

            for (String key : bodys.keySet()) {
                nameValuePairList.add(new BasicNameValuePair(key, bodys.get(key)));
            }
            UrlEncodedFormEntity formEntity = new UrlEncodedFormEntity(nameValuePairList, "utf-8");
            formEntity.setContentType("application/x-www-form-urlencoded; charset=UTF-8");
            request.setEntity(formEntity);
        }

        return httpClient.execute(request);
    }

    /**
     * Post String
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers,
                                      Map<String, String> querys, String body) throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }

    /**
     * Post stream
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPost(String host, String path, String method, Map<String, String> headers,
                                      Map<String, String> querys, byte[] body) throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPost request = new HttpPost(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }

    /**
     * Put String
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers,
                                     Map<String, String> querys, String body) throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (StringUtils.isNotBlank(body)) {
            request.setEntity(new StringEntity(body, "utf-8"));
        }

        return httpClient.execute(request);
    }

    /**
     * Put stream
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @param body
     * @return
     * @throws Exception
     */
    public static HttpResponse doPut(String host, String path, String method, Map<String, String> headers,
                                     Map<String, String> querys, byte[] body) throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpPut request = new HttpPut(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        if (body != null) {
            request.setEntity(new ByteArrayEntity(body));
        }

        return httpClient.execute(request);
    }

    /**
     * Delete
     *
     * @param host
     * @param path
     * @param method
     * @param headers
     * @param querys
     * @return
     * @throws Exception
     */
    public static HttpResponse doDelete(String host, String path, String method, Map<String, String> headers,
                                        Map<String, String> querys) throws Exception {
        HttpClient httpClient = wrapClient(host);

        HttpDelete request = new HttpDelete(buildUrl(host, path, querys));
        for (Map.Entry<String, String> e : headers.entrySet()) {
            request.addHeader(e.getKey(), e.getValue());
        }

        return httpClient.execute(request);
    }

    private static String buildUrl(String host, String path, Map<String, String> querys)
            throws UnsupportedEncodingException {
        StringBuilder sbUrl = new StringBuilder();
        sbUrl.append(host);
        if (!StringUtils.isBlank(path)) {
            sbUrl.append(path);
        }
        if (null != querys) {
            StringBuilder sbQuery = new StringBuilder();
            for (Map.Entry<String, String> query : querys.entrySet()) {
                if (0 < sbQuery.length()) {
                    sbQuery.append("&");
                }
                if (StringUtils.isBlank(query.getKey()) && !StringUtils.isBlank(query.getValue())) {
                    sbQuery.append(query.getValue());
                }
                if (!StringUtils.isBlank(query.getKey())) {
                    sbQuery.append(query.getKey());
                    if (!StringUtils.isBlank(query.getValue())) {
                        sbQuery.append("=");
                        sbQuery.append(URLEncoder.encode(query.getValue(), "utf-8"));
                    }
                }
            }
            if (0 < sbQuery.length()) {
                sbUrl.append("?").append(sbQuery);
            }
        }

        return sbUrl.toString();
    }

    private static HttpClient wrapClient(String host) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        if (host.startsWith("https://")) {
            sslClient(httpClient);
        }

        return httpClient;
    }

    private static void sslClient(HttpClient httpClient) {
        try {
            SSLContext ctx = SSLContext.getInstance("TLS");
            X509TrustManager tm = new X509TrustManager() {
                public X509Certificate[] getAcceptedIssuers() {
                    return null;
                }

                public void checkClientTrusted(X509Certificate[] xcs, String str) {

                }

                public void checkServerTrusted(X509Certificate[] xcs, String str) {

                }
            };
            ctx.init(null, new TrustManager[]{tm}, null);
            SSLSocketFactory ssf = new SSLSocketFactory(ctx);
            ssf.setHostnameVerifier(SSLSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER);
            ClientConnectionManager ccm = httpClient.getConnectionManager();
            SchemeRegistry registry = ccm.getSchemeRegistry();
            registry.register(new Scheme("https", 443, ssf));
        } catch (KeyManagementException ex) {
            throw new RuntimeException(ex);
        } catch (NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
    }


    /**
     * 将结果转换成JSONObject
     *
     * @param httpResponse
     * @return
     * @throws IOException
     */
    public static JSONObject getJson(HttpResponse httpResponse) throws IOException {
        HttpEntity entity = httpResponse.getEntity();
        String resp = EntityUtils.toString(entity, "UTF-8");
        EntityUtils.consume(entity);
        return JSON.parseObject(resp);
    }
}
